package com.youi.shop.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.youi.shop.config.AlipayConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @version 1.0
 * @Author: xxf
 * @CreateDate: 2020/11/12 16:55
 */
@RestController
@RequestMapping("/pay/ali")
@Api(tags = "阿里支付业务接口")
public class AliPayController {

    //!!!!!注意这里是你的APPID沙箱里查看
    //应用id
    private final static String APP_ID = "2016110100783501";

    //!!!!!注意这里是你的应用私钥，在支付宝开发平台助手里（就是刚才生成的私钥）
    //应用私钥
    private final static String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCJjFb2aCEQVOcGqqIw2SBLEOgKyQz1P9nY6aXwWGnrve9T3zuioGe47lsa9ORF0jrXAmXLeeV+ramfKKqK1ckQEuGMTb/qS8nT4SFBO83ud0hvKb7gQb8at0ExZE1eX/m3ST9emdxq4Owwwue3UxkRiNmydtfBNtHdBNcrOUjqmHcf7cXvukex3If2ul68Mi9zGRLwtj1Cld3Dbb6vZquEkmK+wQYH1abzU75a72QyNhI8/c2eaVgqW5l0dG/nvqk2GymX97CyDJZ2LeiGaJHbruTwog5AEyDcg2NiVDJsT79N35Mi1isda8kurqp8Lplee7n3Ioqkb/82sK32YZl7AgMBAAECggEAFfDS9l9J1ucUKxYQ5SXdZtv9h6rmbECRKW6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jJrgHbdch7WFzRWaWxSXYRj1vwpko91bnD7O2IefsmpTrdCiVbHwlQImBd8PCfHh1EVAzL9SfgVVA6Bera4UIuswUY1fr";
    //字符集
    private final static String CHARSET = "UTF-8";

    //!!!!!注意这里是你的支付宝公钥，在沙箱环境中RSA2(SHA256)密钥 弹窗里面的,支付宝公钥
    //应用公钥
    private final static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiYxW9mghEFTnBqqiMNkgSxDoCskM9T/Z2Oml8Fhp673vU987oqBnuO5bGvTkRdI61wJly3nlfq2pnyiqitXJEBLhjE2/6kvJ0+EhQTvN7ndIbym+4EG/GrdBMWRNXl/5t0k/XpncauDsMMLnt1MZEYjZsnbXwTbR3QTXKzlI6ph3H+3F77pHsdyH9rpevDIvcxkS8LY9QpXdw22+r2arhJJivsEGB9Wm81O+Wu9kMjYSPP3NnmlYKluZdHRv576pNhspl/ewsgyWdi3ohmiR267k8KIOQBMg3INjYlQybE+/Td+TItYrHWvJLq6qfC6ZXnu59yKKpG//NrCt9mGZewIDAQAB";

    //!!!!!注意这里是你的支付宝网关，在沙箱环境里查看
    //网关
    private final static String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";

    //格式化
    private final static String FORMAT = "json";
    //签名类型
    private final static String SIGNTYPE = "RSA2";

    /*
     * 获取订单信息
     * */
//    @GetMapping("/getOrderInfo/{totalAmount}/{orderSn}")
    @PostMapping("/getOrderInfo/{totalAmount}/{orderSn}")
    @ApiOperation("支付宝支付")
    public String getOrderInfo(@PathVariable String orderSn, @PathVariable String totalAmount) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGNTYPE);

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("我是测试数据");
        model.setSubject("App支付测试Java");
        model.setOutTradeNo(orderSn);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(totalAmount);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl("商户外网可以访问的异步地址");

        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderSn;
        //付款金额，必填
        String total_amount = totalAmount;
        //订单名称，必填
        String subject = "App支付测试Java";
        //商品描述，可空
        String body = "我是测试数据" ;

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "30m";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");




        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
            System.out.println(response.getBody());
//            return response.getBody();
           return alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/notify_url")
    public String notify_url(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {

            boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGNTYPE);
            //如果验签失败
            if (!flag) {
                return "fail";
            }
            //验签成功后
            //商户的业务逻辑  比如修改订单号
            System.out.println("修改订单成功");

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "success";
    }


    //这里是main方法用来生成alipay_sdk信息
    public static void main(String[] args) {
        AliPayController aliPayController = new AliPayController();
//        aliPayController.getOrderInfo();
    }
}